package ynu.edu.elmservlet.filter;

import ynu.edu.elmservlet.util.JWTUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@WebFilter(filterName = "authFilter", urlPatterns = "/*")
public class AuthFilter implements Filter {
    
    private static final List<String> PUBLIC_PATHS = Arrays.asList(
        "/UserController/login",
        "/UserController/register"
    );

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
        System.out.println("Request URL: " + httpRequest.getRequestURL());
        System.out.println("Request Method: " + httpRequest.getMethod());
        System.out.println("Authorization Header: " + httpRequest.getHeader("Authorization"));
        
        // 处理 OPTIONS 请求
        if (httpRequest.getMethod().equals("OPTIONS")) {
            httpResponse.setStatus(HttpServletResponse.SC_OK);
            return;
        }
        
        // 获取请求路径
        String path = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length());
        System.out.println("Current path: " + path);
        
        // 对公开接口放行
        if (PUBLIC_PATHS.contains(path)) {
            System.out.println("Public path accessed: " + path);
            chain.doFilter(request, response);
            return;
        }

        // 验证token
        String authHeader = httpRequest.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
            try {
                Claims claims = JWTUtil.validateToken(token);
                // 将用户信息存入request
                httpRequest.setAttribute("userId", claims.getSubject());
                chain.doFilter(request, response);
                return;
            } catch (Exception e) {
                System.out.println("Token validation failed: " + e.getMessage());
                httpResponse.setContentType("application/json;charset=UTF-8");
                httpResponse.setStatus(401);
                httpResponse.getWriter().write("{\"message\":\"Invalid token\"}");
                return;
            }
        }

        System.out.println("No authorization header found");
        httpResponse.setContentType("application/json;charset=UTF-8");
        httpResponse.setStatus(401);
        httpResponse.getWriter().write("{\"message\":\"Unauthorized\"}");
    }
} 